package com.snail.readyvr.activity;

import android.content.ContentResolver;
import android.content.Context;
import android.media.AudioManager;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.SeekBar;
import android.widget.TextView;

import com.hwangjr.rxbus.annotation.Subscribe;
import com.hwangjr.rxbus.annotation.Tag;
import com.hwangjr.rxbus.thread.EventThread;
import com.snail.readyvr.R;
import com.snail.readyvr.application.MyApplication;
import com.snail.readyvr.di.component.DaggerPersonalCenterActivityPresenterComponent;
import com.snail.readyvr.di.module.PersonalCenterActivityPresenterModule;
import com.snail.readyvr.event.GetAccountInfo;
import com.snail.readyvr.event.LoginEvent;
import com.snail.readyvr.mvp.contract.PersonalCenterActivityContract;
import com.snail.readyvr.mvp.model.ChangeHeadIconParam;
import com.snail.readyvr.mvp.model.ChangeNickNameParam;
import com.snail.readyvr.mvp.presenter.PersonalCenterActivityPresenter;
import com.snail.readyvr.ui.CommonTopBar;
import com.snail.readyvr.ui.RoundedImageView;
import com.snail.readyvr.util.Constant;
import com.snail.readyvr.util.EventBus;
import com.snail.readyvr.util.LogUtils;
import com.snail.readyvr.util.SPUtils;
import com.snail.readyvr.util.StartActivityUtils;
import com.snail.readyvr.util.StringUtils;
import com.snail.readyvr.util.ToastUtils;
import com.snail.readyvr.util.Utils;
import com.snailvr.tv.Definition;
import com.snailvr.tv.ui.view.FovDialog;
import com.snailvr.tv.ui.view.NavigationDialog;
import com.snailvr.tv.ui.view.ProjectionDialog;
import com.snailvr.tv.util.BrightnessUtil;

import javax.inject.Inject;

import butterknife.BindArray;
import butterknife.BindView;
import butterknife.OnClick;

import static com.snailvr.tv.Definition.KEY_FOV;
import static com.snailvr.tv.Definition.KEY_SNVR_NAVIGATION;

/**
 * Created by MRKING on 2017/1/12.
 */

public class PersonalCenterActivity extends CheckPermissionsActivity implements CommonTopBar.OnClickCommonTopBar, PersonalCenterActivityContract.View {
    @BindView(R.id.personal_center_top_bar)
    CommonTopBar mPersonalCenterTopBar;
    @BindView(R.id.personal_center_user_img)
    RoundedImageView mPersonalCenterUserImg;
    @BindView(R.id.personal_center_user_nickname)
    TextView mPersonalCenterUserNickname;
    @BindView(R.id.personal_center_user_account)
    TextView mPersonalCenterUserAccount;
    @BindView(R.id.personal_center_video_angel)
    TextView mPersonalCenterVideoAngel;
    @BindView(R.id.personal_center_video_tou)
    TextView mPersonalCenterVideoTou;
    @BindView(R.id.personal_center_video_sensor)
    TextView mPersonalCenterVideoSensor;
    @BindView(R.id.personal_center_voice_seek_bar)
    SeekBar mVoiceBar;
    @BindView(R.id.personal_center_light_seek_bar)
    SeekBar mBrightBar;

    @BindArray(R.array.projection_types)
    String[] mProjectionTypes;

    @BindArray(R.array.nav_types)
    String[] mNavTypes;

    private AudioManager mAudioManager;
    /**
     * 最大声音
     */
    private int mMaxVolume;
    /**
     * 当前声音
     */
    private int mVolume;
    /**
     * 当前亮度
     */
    private int mBrightness;

    @Inject
    PersonalCenterActivityPresenter mPresenter;

    @Override
    protected void hasGetAllPermissions() {
        try {
            mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
            mMaxVolume = mAudioManager
                    .getStreamMaxVolume(AudioManager.STREAM_MUSIC);

            mVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);

        } catch (Exception e) {
            e.printStackTrace();
        }

        // 如果开启了自动亮度调节，则关闭之
        if (BrightnessUtil.isAutoBrightness(this)) {
            BrightnessUtil.stopAutoBrightness(this);
        }

        mBrightness = getScreenBrightness();
        Log.i(TAG, "system screen brightness is :" + mBrightness);
        if (mVoiceBar != null) {
            mVoiceBar.setMax(mMaxVolume);
            mVoiceBar.setProgress(mVolume);
        }
        if (mBrightBar != null) {
            mBrightBar.setMax(255);
            mBrightBar.setProgress(mBrightness);
        }
    }

    public int getScreenBrightness() {
        int value = 0;
        ContentResolver cr = getContentResolver();
        try {
            value = Settings.System.getInt(cr, Settings.System.SCREEN_BRIGHTNESS);
        } catch (Settings.SettingNotFoundException e) {

        }
        return value;

    }


    private void changeMode() {
        changeProjection();
        changeNavigation();
        changeFov();
    }

    private void changeProjection() {
        int projectionMode = (int) SPUtils.get(this, Definition.KEY_PROJECTION, Definition.TYPE_180_3D_Left_Right);
        if (projectionMode < mProjectionTypes.length)
            mPersonalCenterVideoTou.setText(mProjectionTypes[projectionMode]);
    }

    private void changeNavigation() {
        int navigationMode = (int) SPUtils.get(this, KEY_SNVR_NAVIGATION, Definition.SNVR_NAVIGATION_SENSOR);

        if (navigationMode < mNavTypes.length)
            mPersonalCenterVideoSensor.setText(mNavTypes[navigationMode]);
    }

    private void changeFov() {
        int fov = (int) SPUtils.get(this, KEY_FOV, Definition.FOV_DEFAULT);
        mPersonalCenterVideoAngel.setText(fov + "°");
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_personal_center;
    }

    @Override
    protected void init() {
        EventBus.getDefault().register(this);
        DaggerPersonalCenterActivityPresenterComponent.builder().applicationComponent(((MyApplication) getApplication()).getApplicationComponent())
                .personalCenterActivityPresenterModule(new PersonalCenterActivityPresenterModule(this))
                .build().inject(this);
        mPersonalCenterTopBar.midTextView.setText(R.string.me);
        mPersonalCenterTopBar.setOnClickCommonTopBar(this);
        /*mPersonalCenterUserNickname.setText(Utils.sUser.getUserName());
        mPersonalCenterUserAccount.setText(Utils.sUser.getEmailOrPhone());*/
        mVoiceBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

                if (!fromUser)
                    return;
                mVolume = progress;
                Log.i(TAG, "current Volume :" + mVolume);
                if (hasGetDangerousPermission && mAudioManager != null)
                    mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, progress, 0);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

        mBrightBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                setScreenBrightness(seekBar.getProgress());
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
        changeMode();
        if(Utils.sUser != null && !StringUtils.isBlank(Utils.sUser.getToken()))
          mPresenter.getAccountInfo(Utils.token);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
            LogUtils.d("KEYCODE_VOLUME_DOWN");
            if (mVolume > 0) {
                mVolume--;
                mVoiceBar.setProgress(mVolume);
                if (hasGetDangerousPermission && mAudioManager != null)
                    mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, mVolume, 0);
            }
            return true;

        } else if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
            LogUtils.d("KEYCODE_VOLUME_UP");
            if (mVolume < mMaxVolume) {
                mVolume++;
                mVoiceBar.setProgress(mVolume);
                if (hasGetDangerousPermission && mAudioManager != null)
                    mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, mVolume, 0);
            }
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        isCheckDangerousPermission = true;
        super.onCreate(savedInstanceState);

    }

    //设置屏幕亮度的函数
    private void setScreenBrightness(int brightness) {
        // 根据当前进度改变屏幕亮度
        if (hasGetDangerousPermission)
            Settings.System.putInt(getContentResolver(),
                    Settings.System.SCREEN_BRIGHTNESS, brightness);
    }

    @OnClick({R.id.personal_center_user_layout, R.id.personal_center_has_buy, R.id.personal_center_video_angel_layout, R.id.personal_center_video_tou_layout, R.id.personal_center_video_sensor_layout, R.id.personal_center_setting})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.personal_center_user_layout:
                if (Utils.sUser != null && !StringUtils.isBlank(Utils.sUser.getToken())) {
                    //StartActivityUtils.startPersonalCenterActivity(this);
                    StartActivityUtils.startMeActivity(this);
                    overridePendingTransition(R.anim.scale_dialog_enter, 0);
                } else {
                    ToastUtils.show(this, R.string.no_login_tip);
                    StartActivityUtils.startNoLoginActivity(this, LoginEvent.FROM_ME_LOGIN);
                }

                break;
            case R.id.personal_center_has_buy:
                break;
            case R.id.personal_center_video_angel_layout:
                final
                FovDialog.Builder builder = new FovDialog.Builder(this, null);
                builder.addSubmitListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int mFov = (int) v.getTag();
                        SPUtils.put(PersonalCenterActivity.this, KEY_FOV, mFov);
                        changeFov();
                    }
                }).show();

                break;
            case R.id.personal_center_video_tou_layout:
                ProjectionDialog.Builder builder1 = new ProjectionDialog.Builder(this);
                final android.support.v7.app.AlertDialog dialog1 = builder1.show();
                builder1.addOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog1.dismiss();
                        changeProjection();
                    }
                });
                break;
            case R.id.personal_center_video_sensor_layout:
                NavigationDialog.Builder builder2 = new NavigationDialog.Builder(this);
                final android.support.v7.app.AlertDialog dialog2 = builder2.show();
                builder2.addOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog2.dismiss();
                        changeNavigation();
                    }
                });
                break;
            case R.id.personal_center_setting:
                StartActivityUtils.startSettingsActivity(this);
                overridePendingTransition(R.anim.scale_dialog_enter, 0);
                break;
        }
    }

    @Override
    public void onClickLeftView() {
        finish();
    }

    @Override
    public void onClickRightView() {

    }

    @Override
    public void getAccountInfoSuccess() {
        if (Utils.myAccountInfo != null) {
            mPersonalCenterUserNickname.setText(Utils.myAccountInfo.getNickname());
            mPersonalCenterUserAccount.setText(Utils.myAccountInfo.getNumber());
            mPersonalCenterUserImg.setImageResource(Utils.getHeadIconRes(Utils.myAccountInfo.getHead_icon()));
        }
    }

    @Subscribe(thread = EventThread.MAIN_THREAD, tags = {@Tag(Constant.BusTag.GET_ACCOUNT_TAG)})
    public void getAccountInfo(GetAccountInfo accountinfo){
        if(accountinfo != null && accountinfo.getType() == GetAccountInfo.TYPE_SUCCESS){
            getAccountInfoSuccess();
        }
    }

    @Override
    public void showProgress() {

    }

    @Override
    public void dismissProgress() {

    }

    @Override
    public void error(Throwable throwable) {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(thread = EventThread.MAIN_THREAD, tags = {@Tag(Constant.BusTag.CHANGE_NICKNAME_TAG)})
    public void onChangeNickName(ChangeNickNameParam param) {
        if (param == null)
            return;
        mPersonalCenterUserNickname.setText(param.getNickname());

    }

    @Subscribe(thread = EventThread.MAIN_THREAD, tags = {@Tag(Constant.BusTag.CHANGE_HEADICON_TAG)})
    public void onChangeHeadIcon(ChangeHeadIconParam param) {
        if (param == null)
            return;
        mPersonalCenterUserImg.setImageResource(Utils.getHeadIconRes(param.getHead_icon()));

    }

    @Override
    public void finish() {
        this.setResult(Definition.PLAY_SETTING_RESULT_CODE);
        super.finish();
    }
}
